package com.leyou.user.service;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.AddressDTO;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 实现用户数据的校验，主要包括对：
     * 手机号、用户名的唯一性校验。当用户注册时，会输入用户名或手机号，此时页面会异步请求服务端，服务端接收数据，校验数据的唯一性。
     * @param data
     * @param type 1.用户名， 2.手机
     * @return
     */
    public Boolean checkData(String data, Integer type) {
        //查询条件
        User record = new User();

        //判断字段类型
        switch (type){
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        //查询数据
        return userMapper.selectCount(record)==0;
    }


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private static final String KEY_PREFIX = "user:verify:phone";

    public void sendCode(String phone) {
        // 验证手机号格式
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        // 生成验证码
        String code = RandomStringUtils.randomNumeric(6);
        // 保存验证码到redis
        String key = KEY_PREFIX + phone;
        redisTemplate.opsForValue().set(key,code);
        // 发送RabbitMQ消息到ly-sms
        Map<String,String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);
        amqpTemplate.convertAndSend(
                MQConstants.Exchange.SMS_EXCHANGE_NAME,
                MQConstants.RoutingKey.VERIFY_CODE_KEY,
                msg);
    }



    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 用户页面填写数据，发送表单到服务端，服务端实现用户注册功能。
     * 需要对用户密码进行加密存储，使用MD5加密，
     * 加密过程中使用随机码作为salt加盐。另外还需要对用户输入的短信验证码进行校验
     * @param user 用户信息
     * @param code 验证码
     */
    public void register(User user, String code) {

        // 验证短信验证码
        String key = KEY_PREFIX + user.getPhone();
        String cachecode = redisTemplate.opsForValue().get(key);

        if (!StringUtils.equals(cachecode,code)){
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //TODO 校验用户数据

        // 对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 写入数据库
        int count = userMapper.insertSelective(user);
        if (count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }




    public UserDTO queryByUsernameAndPassword(String username, String password) {
        //查询用户
        User record = new User();
        record.setUsername(username);

        User user = userMapper.selectOne(record);
        //判断用户是否存在
        if (user == null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //校验密码
        if (!passwordEncoder.matches(password,user.getPassword())) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //用户名和密码都正确，返回用户
        return BeanHelper.copyProperties(user,UserDTO.class);
    }

    public AddressDTO queryAddressById(Long userId, Long id) {

        AddressDTO address = new AddressDTO();
        address.setId(id);
        address.setUserId(userId);
        address.setStreet("航头镇航头路18号传智播客 3号楼");
        address.setCity("上海");
        address.setDistrict("浦东新区");
        address.setAddressee("虎哥");
        address.setPhone("15800000000");
        address.setProvince("上海");
        address.setZipCode("210000");
        address.setIsDefault(true);
        return address;
    }
}
